package com.ruitu.mall_98;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.MenuItem;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.beanu.arad.Arad;
import com.beanu.arad.base.my_base.Config;
import com.beanu.arad.utils.AppUtils;
import com.beanu.arad.utils.SizeUtils;
import com.beanu.arad.utils.ToastUtils;
import com.beanu.arad.utils.UIUtils;
import com.beanu.arad.widget.BottomNavigationViewEx;
import com.beanu.arad.widget.NoScrollViewPager;
import com.beanu.arad.widget.progressactivity.ProgressLayout;
import com.hjq.permissions.Permission;
import com.ruitu.mall_98.activity.ServiceAndPrivacyActivity;
import com.ruitu.mall_98.base.MyApp;
import com.ruitu.mall_98.fragment.MainHomeFragment;
import com.ruitu.mall_98.fragment.MsgFragment;
import com.ruitu.mall_98_1.dao.api.APIRetrofit;
import com.ruitu.router_module.A_Rutils;
import com.ruitu.router_module.AppHolder;
import com.ruitu.router_module.CommonUtils;
import com.ruitu.router_module.bean.EventModel;
import com.ruitu.router_module.bean.api.BaseResult;
import com.ruitu.router_module.bean.api.SubscriberImpl;
import com.ruitu.router_module.bean.map_location.BaseMapActivity;
import com.ruitu.router_module.bean.map_location.LocationService;
import com.ruitu.router_module.bean.map_location.MyLocationListener;
import com.ruitu.router_module.bean.mine.Version;
import com.ruitu.router_module.utils.PermissionUtil;

import q.rorbin.badgeview.QBadgeView;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class MainActivity extends BaseMapActivity {
    private BottomNavigationViewEx bnve;
    private NoScrollViewPager vp;
    private RelativeLayout rl_content;//activity布局
    private QBadgeView qBadgeView;//小红点

    private VpAdapter adapter;

    private LocationService locationService;

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_app_main;
    }

    @Override
    protected ProgressLayout findProgressLayout() {
        return null;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusBar(0);
        bnve = findViewById(R.id.bnve);
        vp = findViewById(R.id.vp);
        rl_content = findViewById(R.id.rl_content);

        vp.setOffscreenPageLimit(9);
        vp.setScanScroll(false);

        bnve.enableAnimation(false);
        bnve.enableShiftingMode(false);
        bnve.enableItemShiftingMode(false);

        bnve.setIconsMarginTop(SizeUtils.dp2px(10));
        bnve.setIconSize(23, 23);
        bnve.setTextSize(10);
        bnve.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                return true;
            }
        });

        adapter = new VpAdapter(getSupportFragmentManager());
        vp.setAdapter(adapter);
        bnve.setupWithViewPager(vp);

        qBadgeView = new QBadgeView(this);
//        addBadge(2,99);

        vp.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                if (position == 3) {
                    if (CommonUtils.isLoginToActivity(MainActivity.this)) {

                    } else {
                        ToastUtils.showShort("请先登录");
                    }
                }
            }
        });

        mListener = new MyLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation loc) {
                super.onReceiveLocation(loc);
//                MyLocationData locData = new MyLocationData.Builder()
//                        .accuracy(loc.getRadius())
//                        // 此处设置开发者获取到的方向信息，顺时针0-360
//                        .direction(100).latitude(loc.getLatitude())
//                        .longitude(loc.getLongitude()).build();
//                mBaiduMap.setMyLocationData(locData);

                if (isFirsLoc) {
                    isLocSuccess = true;
                    isFirsLoc = false;
                }

                if (null != loc) {
                    Arad.bus.post(new EventModel(18120351, loc));
                }
            }
        };

        locationService = ((MyApp) getApplication()).locationService;
        locationService.registerListener(mListener);

        reqNewVersion();
    }

    public void addBadge(int position, final int number) {// add badge
        int num = number > 99 ? 99 : number;
        if (number == 0) {
            qBadgeView.hide(true);
        } else {
            qBadgeView.setBadgeNumber(num)
                    .setGravityOffset(10, 3, true)
                    .bindTarget(bnve.getBottomNavigationItemView(position))
                    .setBadgeTextSize(10, true)
//                    .setOnDragStateChangedListener(new Badge.OnDragStateChangedListener() {
//                        @Override
//                        public void onDragStateChanged(int dragState, Badge badge, View targetView) {
//                            vp.setCurrentItem(2, true);
//                            if (Badge.OnDragStateChangedListener.STATE_SUCCEED == dragState) {
////                            Toast.makeText(BadgeViewActivity.this, R.string.tips_badge_removed, Toast.LENGTH_SHORT).show();
//                            }
//                        }
//                    })
            ;
        }
    }

    private void reqNewVersion() {//检查新版本
        APIRetrofit.getDefault().reqNewVersion().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SubscriberImpl<BaseResult<Version>>() {
                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(final BaseResult<Version> baseResult) {
                        if (baseResult.isSuccess()) {
                            final Version bean = baseResult.getData();
                            if (bean.getCode() > AppUtils.getAppVersionCode()) {//说明服务器上有新版本
                                UIUtils.showAlertDialog(getSupportFragmentManager(), "发现新版本", bean.getContent(), "立即更新"
                                        , "取消", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                Uri uri = Uri.parse(Config.BASE_URL + bean.getUrl());
                                                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                                                startActivity(intent);
                                            }
                                        }, null);
                            }
                        } else {
                            ToastUtils.showShortSafe(baseResult.getMsg());
                        }
                    }
                });
    }

    private boolean isCheckPession = false;

    @Override
    protected void onResume() {
        super.onResume();
        if (!CommonUtils.isLogin() && vp.getCurrentItem() == 3) {
            vp.setCurrentItem(0);
        }
        if (MainHomeFragment.IS_NEED_LODCATION && isCheckPession) {
            startLoc();
            isCheckPession = false;
        }
    }

    public void startLoc() {// 开始定位
        PermissionUtil.handleMultiPermission(this, "定位", new PermissionUtil.PermissionListener() {
            @Override
            public void onPermissionOk(boolean isOk) {
                if (isOk) locationService.start();// 定位SDK
            }

            @Override
            public void onOpenPermissionPage(boolean isOpen) {
                if (isOpen) isCheckPession = true;
            }
        }, Permission.ACCESS_COARSE_LOCATION, Permission.ACCESS_FINE_LOCATION);
    }

    public void setStatusBar(float a) {
        mImmersionBar.statusBarAlpha(a);
        setStatusBar();
    }

    public void setCurrVp(int index) {//切换vp页面
        vp.setCurrentItem(index, true);
    }

    private class VpAdapter extends FragmentPagerAdapter {

        public VpAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            if (position == 0) {//首页
                return MainHomeFragment.newInstance();
            } else if (position == 1) {//分类
                Fragment fragment = A_Rutils.getFragment("com.ruitu.mall_98_1.product.fragment.CategoryFragment");
                if (null != fragment) {
                    return fragment;
                } else {
                    ToastUtils.showShort("加载MineFragment失败");
                }
            } else if (position == 2) {//2018.12.27 新加的消息页面
                return MsgFragment.newInstance();
            } else if (position == 3) {//购物车 com.ruitu.mall_98_2.cart.CartFragment
                Fragment fragment = A_Rutils.getFragment("com.ruitu.mall_98_2.cart.CartFragment");
                if (null != fragment) {
                    return fragment;
                } else {
                    ToastUtils.showShort("加载MineFragment失败");
                }
            } else if (position == 4) {//我的
                Fragment fragment = A_Rutils.getFragment("com.ruitu.mall_98_2.mine.MineFragment");
                if (null != fragment) {
                    return fragment;
                } else {
                    ToastUtils.showShort("加载MineFragment失败");
                }
            }

            return MainHomeFragment.newInstance();
        }

        @Override
        public int getCount() {
            return 5;
        }
    }

    private long waitTime = 2000;
    private long touchTime = 0;

    @Override
    public void onBackPressed() {
        if (null != vp && vp.getCurrentItem() == 0) {
            long currentTime = System.currentTimeMillis();
            if ((currentTime - touchTime) >= waitTime) {
                ToastUtils.showShortSafe("再按一次退出程序");
                touchTime = currentTime;
            } else {
                Intent backHome = new Intent(Intent.ACTION_MAIN);//启动一个意图,回到桌面
                backHome.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                backHome.addCategory(Intent.CATEGORY_HOME);
                startActivity(backHome);
//                System.exit(0);
//                super.onBackPressed();
            }
        } else {
            vp.setCurrentItem(0);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AppHolder.instance().setUser(null);
    }
}
